package util;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: tum0r
 * Package Name: util
 * Time: 2019-03-10 Sunday 14:17:52
 */
public class AddressHandle {
    public String handle(String ip) {
        String[] address = getAddress();
        for (String addr : address) {
            Pattern pattern = Pattern.compile("((\\d+\\.){3}(\\d+){1})|((\\d+:){1,}(\\d+)%lo)");
            Matcher matcher = pattern.matcher(addr);
            while (matcher.find()) {
                if (ip.equals(matcher.group().replace("%lo", ""))) {
                    ip = "127.0.0.1";
                }
            }
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    public static String[] getAddress() {
        try {
            Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
            List<List<String>> list = new ArrayList<>();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
                List<String> temp = new ArrayList<>();
                temp.add(networkInterface.getName());
                temp.add(networkInterface.getDisplayName());
                temp.add(networkInterface.getInterfaceAddresses().toString());
                list.add(temp);
            }
            String[] result = new String[list.size()];
            Iterator<List<String>> out = list.iterator();
            int count = 0;
            while (out.hasNext()) {
                Iterator<String> in = out.next().iterator();
                StringBuilder stringBuilder = new StringBuilder();
                while (in.hasNext()) {
                    stringBuilder.append(in.next()).append(" ");
                }
                result[count] = stringBuilder.toString().trim();
                count++;
            }
            return result;
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }
}
